<template>
  <div class="login-container">
    <a-card class="login-card" title="Easy Admin 登录">
      <a-form :model="loginForm" @submit="handleSubmit">
        <a-form-item field="username" label="用户名" validate-trigger="blur" :rules="[{ required: true, message: '请输入用户名' }]">
          <a-input v-model="loginForm.username" placeholder="请输入用户名" />
        </a-form-item>
        <a-form-item field="password" label="密码" validate-trigger="blur" :rules="[{ required: true, message: '请输入密码' }]">
          <a-input-password v-model="loginForm.password" placeholder="请输入密码" />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit" long :loading="loading">登录</a-button>
        </a-form-item>
      </a-form>
    </a-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { Message } from '@arco-design/web-vue'
import { useUserStore } from '../stores/user'
import request from '../api/request'

const router = useRouter()
const userStore = useUserStore()

const loginForm = ref({
  username: '',
  password: ''
})

const loading = ref(false)

const handleSubmit = async () => {
  try {
    loading.value = true
    const response = await request.post('/api/SysUser/login', loginForm.value)
    
    if (response.data.token) {
      userStore.setToken(response.data.token)
      // 显示后端返回的成功消息
      if (response.message) {
        Message.success(response.message)
      }
      router.push('/dashboard')
    }
  } catch (error) {
    Message.error(error.message || '登录失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: var(--color-neutral-2);
}

.login-card {
  width: 100%;
  max-width: 400px;
  margin: 0 20px;
}
</style>